package mySeleniumDriver;

import com.sun.jna.Pointer;
import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.platform.win32.WinDef.HWND;

public class CheckWindowPresence extends BaseClass {

  // Equivalent JNA mappings
  public interface User32 extends StdCallLibrary {
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

    HWND SetForegroundWindow(Pointer wnd);

    interface WNDENUMPROC extends StdCallCallback {
      boolean callback(Pointer hWnd, Pointer arg);
    }

    boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);

    boolean PostMessage(Pointer hwndParent, String msg, String wParam, String lParam);

    Pointer FindWindowEx(Pointer hwndParent, String hwndChildAfter, String lpszClass,
        String lpszWindow);

    int GetWindowTextA(Pointer hWnd, byte[] lpString, int nMaxCount);

  }


  public boolean isWindowPresentWithTitle(String winTitle, int noOfIterations)
      throws InterruptedException {

    final String winToCheck = winTitle;
    boolean winPresent = false;

    for (int i = 0; i < noOfIterations; i++) {
      log("info", "Checking for window with title {" + winToCheck + "} in iteration " + i);
      final User32 user32 = User32.INSTANCE;

      winPresent = user32.EnumWindows(new User32.WNDENUMPROC() {



        int count;


        public boolean callback(Pointer hWnd, Pointer userData) {

          // log("info", "LOOP OUT ");

          byte[] windowText = new byte[512];
          user32.GetWindowTextA(hWnd, windowText, 512);
          String wText = Native.toString(windowText);
          wText = (wText.isEmpty()) ? "" : wText;

          // log("info", "Checking window title " + wText);
          if (wText.contains(winToCheck)) {
            log("info", "Found window with title " + wText + ", count= " + ++count);
            user32.SetForegroundWindow(hWnd);
            return false;
            // return true;
            // **************************************************//
            // NEED CODE HERE TO ITERATE THROUGH ELEMENTS OF THIS PARTICULAR WINDOW, READ THE
            // MESSAGE TEXT AND CLICK OK BUTTON.
            // **************************************************//

          }

          return true;

        }

      }, null);


      if (winPresent == false) break;
      Thread.sleep(500);

    }



    return !winPresent;

  }

}
